package com.snj.visangedu;


import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ViewFlipper;

import com.snj.visangedu.lib.CustomHttpClient;
import com.snj.visangedu.lib.Global;
import com.snj.visangedu.lib.NewsLib;

public final class ContentFragment extends Fragment {
	private static final String KEY_CONTENT = "ContentFragment:Content";
	
	private final String tag = "ContentFragment";
	
	ProgressDialog ProgDlg = null;
	
	public String mContent = "???";
	public int mPosition = 0; 
	public int mNewsIndex = 0;
	
	
	String[] contents = null;
	int contentlen = 0;
	String id = "";
	
	public int newsid = 1;
	
	int currentpage = 0;
	
	public static ContentFragment newInstance(int _newsid, String content, int newsindex, int position) {
		ContentFragment fragment = new ContentFragment();

		fragment.mContent = content;
		fragment.mPosition = position;
		fragment.mNewsIndex = newsindex;
		
		fragment.newsid = _newsid;
		
		return fragment;
	}
	
	View v = null;
	ViewFlipper vf = null;
	ImageView low_iv = null;
	
	RelativeLayout rlly_arrowleft = null;
	RelativeLayout rlly_arrowright = null;
	
	ImageView img_arrowleft = null;
	ImageView img_arrowright = null;
	
	ImageView img_arrowdown = null;
	ImageView img_arrowup = null;
	ImageView img_close = null;
	
	Context context = null;
	private int m_nPreTouchPosX = 0;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		
		v = inflater.inflate(R.layout.fragment_content, container, false);
		context = v.getContext();
		
		rlly_arrowleft = (RelativeLayout)v.findViewById(R.id.rlly_leftarrow);
		rlly_arrowright = (RelativeLayout)v.findViewById(R.id.rlly_rightarrow);

		img_arrowleft = (ImageView)v.findViewById(R.id.img_arrowleft);
		img_arrowright = (ImageView)v.findViewById(R.id.img_arrowright);
		
		
		img_arrowleft.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				MovewPreviousView();
			}
		});
		
		img_arrowright.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				MoveNextView();
			}
		});
		
		
		
		
		vf = (ViewFlipper)v.findViewById(R.id.vf_partnerimg);
		vf.setOnTouchListener(MyTouchListener);
		
		vf.setVisibility(View.INVISIBLE);
		
		
		if(mNewsIndex > -1)
		{
			Log.d(tag, "newsid : " + newsid + ", mNewsIndex : " + mNewsIndex + ", size : " + NewsLib.newsloader[newsid].GetNewsArray().size());
			low_iv = (ImageView)v.findViewById(R.id.img_preview);
			low_iv.setImageBitmap(NewsLib.newsloader[newsid].GetNewsArray().get(mNewsIndex).GetNewsImage());// Global.mNews.get(mNewsIndex).GetCover());
		}
				
		Log.d(tag, "pos : " + mPosition);
		if(mPosition == 1)	// 占쏙옙占쏙옙 占쏙옙占쏙옙占쏙옙占쏙옙 占쏙옙占쏘데 占쏙옙占쏙옙占쌓몌옙트占쏙옙 占쏙옙占� (占쏙옙화占쏙옙 占싱뱄옙占쏙옙 占쌀뤄옙占승댐옙)
		{
			new AsyncTask<String, String, String>() {
				
				
				Bitmap img = null;
				
				
	
				@Override
				protected void onPreExecute() {
					// TODO Auto-generated method stub
					super.onPreExecute();
					
					//ProgDlg = ProgressDialog.show(getActivity(), "", "占쏙옙占쏙옙 占싸듸옙占쏙옙占쌉니댐옙.\n占쏙옙첩占� 占쏙옙慕占쏙옙玲占쏙옙占�.", true, false);
					ProgDlg = new ProgressDialog(getActivity());
					ProgDlg.setIndeterminate(true);
					ProgDlg.setCancelable(false);
					ProgDlg.show();
					ProgDlg.setContentView(R.layout.custom_progress);
					
				}



				@Override
				protected String doInBackground(String... params) {
					// TODO Auto-generated method stub
					
					String result = "";
	            	JSONObject resultobj = null;
	            	String imgsrc = "";
	            	
	            	if(mContent == null)
	            		return null;
	            	
	            	
	            	ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
					
	            	
					postParameters.clear();
					postParameters.add(new BasicNameValuePair("no", mContent));
					postParameters.add(new BasicNameValuePair("newsid", String.format("%d", newsid + 1)));
						
					Log.d(tag, "called");
					Log.d(tag, "parameter : " + postParameters.toString());
						
					try {
						result = CustomHttpClient.executeHttpPost(Global.contenturl, postParameters);	
						Log.d(tag, "result : " + result);
						resultobj = new JSONObject(result);
							
						Log.d(tag, "result : " + result);
						
						JSONObject obj = new JSONObject(result);
						contentlen = obj.getInt("contentlength");
						
						contents = obj.getString("contents").split(",");
						id = obj.getString("id");
												
						String filename = "";
						String fullpath = "";
						
						if(contentlen <= 7)
						{
							for(int i=0; i<contentlen; i++)
							{
								
								filename = contents[i].replace(".jpg", ".venews").replace(".png", ".venews") + obj.getString("updatever");
								fullpath = "/visangedu/news" + (newsid + 1) + "/contents/" + id + "/" + filename;
								
								if(!Global.FileExist(fullpath, ""))
								{
									Log.d(tag, "download from server.....");
									img = CustomHttpClient.downloadBitmap(Global.vnpbaseurl + "contents" + (newsid + 1) + "/" + id + "/" + contents[i]);
									Global.saveBitmaptoJpeg(img, "/visangedu/news" + (newsid + 1) + "/contents/" + id + "/", filename);
								}
								else
								{
									img = BitmapFactory.decodeFile(Global.ex_storage + fullpath);
									Log.d(tag, "Load From : " + Global.ex_storage + fullpath);
								}
								
								if(img == null)
								{
									Log.d(tag, "download from server..... : " + Global.vnpbaseurl + "contents" + (newsid + 1) + "/" + id + "/" + contents[i]);
									img = CustomHttpClient.downloadBitmap(Global.vnpbaseurl + "contents" + (newsid + 1) + "/" + id + "/" + contents[i]);
									Global.saveBitmaptoJpeg(img, "/visangedu/news" + (newsid + 1) + "/contents/" + id + "/", filename);
								}
								
								//img = CustomHttpClient.downloadBitmap(Global.vnpbaseurl + "contents/" + id + "/" + contents[i]);
								publishProgress("");
							}
						}
						else
						{
							for(int i=0; i<4; i++)
							{	
								filename = contents[i].replace(".jpg", ".venews").replace(".png", ".venews") + obj.getString("updatever");
								fullpath = "/visangedu/news" + (newsid + 1) + "/contents/" + id + "/" + filename;
								
								
								if(!Global.FileExist(fullpath, ""))
								{
									Log.d(tag, "download from server.....");
									img = CustomHttpClient.downloadBitmap(Global.vnpbaseurl + "contents" + (newsid + 1) + "/" + id + "/" + contents[i]);
									Global.saveBitmaptoJpeg(img, "/visangedu/news" + (newsid + 1) + "/contents/" + id + "/", filename);
								}
								else
								{
									img = BitmapFactory.decodeFile(Global.ex_storage + fullpath);
								}
								
								//img = CustomHttpClient.downloadBitmap(Global.vnpbaseurl + "contents/" + id + "/" + contents[i]);
								publishProgress("N");
							}
							for(int i=0; i<3; i++)
							{	
								filename = contents[contentlen - 1 - i].replace(".jpg", ".venews").replace(".png", ".venews") + obj.getString("updatever");
								fullpath = "/visangedu/news" + newsid + "/contents/" + id + "/" + filename;
								Log.d(tag, "filename : " + filename);
								
								if(!Global.FileExist(fullpath, ""))
								{
									Log.d(tag, "download from server.....");
									img = CustomHttpClient.downloadBitmap(Global.vnpbaseurl + "contents" + (newsid + 1) + "/" + id + "/" + contents[contentlen - 1 - i]);
									Global.saveBitmaptoJpeg(img, "/visangedu/news" + newsid + "/contents" + (newsid + 1) + "/" + id + "/", filename);
								}
								else
								{
									img = BitmapFactory.decodeFile(Global.ex_storage + fullpath);
								}
								
								//img = CustomHttpClient.downloadBitmap(Global.vnpbaseurl + "contents/" + id + "/" + contents[contentlen - 3 + i]);
								publishProgress("P");
							}
						}
						
						
					}
					catch(Exception e)
					{
						e.printStackTrace();
					}
					return null;
				}
				
				
	
				@Override
				protected void onProgressUpdate(String... values) {
					// TODO Auto-generated method stub
					super.onProgressUpdate(values);
					
					
					
					ImageView iv2 = new ImageView(v.getContext());		
					iv2.setImageBitmap(img);
					
					if(values[0].equals("N") || values[0].equals(""))
					{
						vf.addView(iv2);
					}
					else if(values[0].equals("P"))
					{
						vf.addView(iv2, 0);
					}
					
					
				}
	
	
	
				@Override
				protected void onPostExecute(String result) {
					// TODO Auto-generated method stub
					super.onPostExecute(result);
					
					ProgDlg.dismiss();
					
					vf.setVisibility(View.VISIBLE);
					low_iv.setVisibility(View.INVISIBLE);
					currentpage = 0;
			        
				}
	        	
			}.execute("");
		}	
		
		
		return v;
		
	}
	
	
	private void MoveNextView()
    {
		Log.d(tag, "Current Page : " + vf.getDisplayedChild());
		
		if(contentlen > 7)
		{
		
			final ImageView civ = (ImageView)vf.getChildAt((vf.getDisplayedChild() + 4) % 7);
			
			//currentpage = (currentpage + 1) % contentlen;
			
			Log.d(tag, "targetpage : " + ((vf.getDisplayedChild() + 4) % 7));
			Log.d(tag, "load image : " + (currentpage + 4) % contentlen);
			
			new AsyncTask<String, String, String>()
			{
					
				Bitmap tempimg = null;
				
				@Override
				protected String doInBackground(String... params) {
					// TODO Auto-generated method stub
					
					Log.d(tag, "Download[" + (currentpage + 4) % contentlen + "] : " + contents[(currentpage + 4) % contentlen]);
					tempimg = CustomHttpClient.downloadBitmap(Global.vnpbaseurl + "contents" + (newsid + 1) + "/" + id + "/" + contents[(currentpage + 4) % contentlen]);
					currentpage++;
					return null;
				}
	
				@Override
				protected void onPostExecute(String result) {
					// TODO Auto-generated method stub
					super.onPostExecute(result);
					
					try
					{
						Bitmap b = ((BitmapDrawable)civ.getDrawable()).getBitmap();
						
						if(b != null)
							b.recycle();

						
						civ.setImageBitmap(tempimg);
					}
					catch(Exception e)
					{
						e.printStackTrace();
					}
				}
			}.execute("");
		}
		else
		{
			currentpage++;
		}
		
		
		
		
		
		vf.setInAnimation(AnimationUtils.loadAnimation(context,	R.anim.appear_from_right));
		vf.setOutAnimation(AnimationUtils.loadAnimation(context, R.anim.disappear_to_left));
		vf.showNext();
    }
    
    private void MovewPreviousView()
    {
    	Log.d(tag, "Current Page : " + vf.getDisplayedChild());
    	
    	if(contentlen > 7)
		{
	    	Log.d(tag, "targetpage : " + ((vf.getDisplayedChild() + 3) % 7));
			
			currentpage--;
			if(currentpage < 0) currentpage = contentlen - 1;
			
			int loadindex = ((currentpage - 3) < 0 ? (contentlen + currentpage - 3) : currentpage - 3);
			Log.d(tag, "load image : " + loadindex);
			Log.d(tag, "load image : " + contents[loadindex]);
			
	    	
	    	final ImageView civ = (ImageView)vf.getChildAt(((vf.getDisplayedChild() + 3) % 7));
			
			//currentpage = (currentpage + 1) % contentlen;
			
			new AsyncTask<Integer, String, String>()
			{
					
				Bitmap tempimg = null;
				
				@Override
				protected String doInBackground(Integer... params) {
					// TODO Auto-generated method stub
					
					String filename = "";
					String fullpath = "";
					
					tempimg = CustomHttpClient.downloadBitmap(Global.vnpbaseurl + "contents" + (newsid + 1) + "/" + id + "/" + contents[params[0]]);
					
					return null;
				}
	
				@Override
				protected void onPostExecute(String result) {
					// TODO Auto-generated method stub
					super.onPostExecute(result);
					
					Bitmap b = ((BitmapDrawable)civ.getDrawable()).getBitmap();
					
					if(b != null)
						b.recycle();
					civ.setImageBitmap(tempimg);
				}
				
				
				
			}.execute(loadindex);
			
		}
		
		
		
		
    	vf.setInAnimation(AnimationUtils.loadAnimation(context,	R.anim.appear_from_left));
    	vf.setOutAnimation(AnimationUtils.loadAnimation(context, R.anim.disappear_to_right));
    	vf.showPrevious();
    	
    	
    }
	
	View.OnTouchListener MyTouchListener = new View.OnTouchListener()
    {
    	public boolean onTouch(View v, MotionEvent event) 
    	{
    		if (event.getAction() == MotionEvent.ACTION_DOWN)
    		{
    			m_nPreTouchPosX = (int)event.getX();
    		}
    		
    		if (event.getAction() == MotionEvent.ACTION_UP)
    		{
    			int nTouchPosX = (int)event.getX();
    			
    			if (nTouchPosX < m_nPreTouchPosX)
    			{
    				MoveNextView();
    			}
    			else if (nTouchPosX > m_nPreTouchPosX)
    			{
    				MovewPreviousView();
    			}
    			
    			m_nPreTouchPosX = nTouchPosX;
    		}
    		
            return true;
        }
    };

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		Log.d("TestFragment", "resume : " + mContent);
	}


	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
		
	}
	
	
	
}
